import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

///下列中两个NotificationListener进行了嵌套，
///
///子NotificationListener的onNotification回调返回了false，表示不阻止冒泡，
///所以父NotificationListener仍然会受到通知，所以控制台会打印出通知信息；
///
///如果将子NotificationListener的onNotification回调的返回值改为true，
///则父NotificationListener便不会再打印通知了，因为子NotificationListener已经终止通知冒泡了。
///

class NotificationRoute extends StatefulWidget {
  @override
  NotificationRouteState createState() {
    return NotificationRouteState();
  }
}

class NotificationRouteState extends State<NotificationRoute> {
  String _msg = "";

  @override
  Widget build(BuildContext context) {
    //监听通知
    return NotificationListener<MyNotification>(
      onNotification: (notification) {
        print("父层 ${notification.msg}"); //打印通知
        return false;
      },
      child: NotificationListener<MyNotification>(
        onNotification: (notification) {
          setState(() {
            _msg += notification.msg + "  ";
          });
          print("子层 ${notification.msg} 我返回true 进行拦截"); //打印通知
          return true; //返回true 代表拦截 将不会再次传递
        },
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Builder(
                builder: (context) {
                  return ElevatedButton(
                    //按钮点击时分发通知
                    onPressed: () => MyNotification("Hi").dispatch(context),
                    child: Text("Send Notification 有效"),
                  );
                },
              ),

              //这个点击是无效的可以看源码 dispatch中的visitAncestor方法中的
              // if (element is StatelessElement) 条件
              ElevatedButton(
                //按钮点击时分发通知
                onPressed: () => MyNotification("Hi").dispatch(context),
                child: Text("Send Notification 无效 "),
              ),

              Text(_msg)
            ],
          ),
        ),
      ),
    );
  }
}

class MyNotification extends Notification {
  MyNotification(this.msg);

  final String msg;
}
